
const fs = require('fs').promises;
const path = require('path');
const xml2js = require('xml2js');
import moment from 'moment';

async function parseXMLFile(filePath: any) {
    const data = await fs.readFile(filePath, 'utf8');
    const parser = new xml2js.Parser();
    const result = await parser.parseStringPromise(data);
    return result;
}

async function processDirectory(directoryPath: any) {
    try {
        const entries = await fs.readdir(directoryPath, { withFileTypes: true });

        for (const entry of entries) {
            const fullPath = path.join(directoryPath, entry.name);

            if (entry.isDirectory()) {
                // 递归处理子目录
                await processDirectory(fullPath);
            } else if (entry.isFile() && path.extname(entry.name).toLowerCase() === '.xml') {

                const parsedData = await parseXMLFile(fullPath);

                var t0 = new Date(parsedData.i.BililiveRecorderRecordInfo[0].$.start_time);

                var str = "";
                parsedData.i.d && parsedData.i.d.forEach((item: any) => {
                    var raw = item["$"].raw && JSON.parse(item["$"].raw);
                    var t = new Date(raw[9].ts * 1000);
                    var diff = t.getTime() - t0.getTime();
                    var txt = raw[1].replace(/,/g, "，");
                    str += "[" + item["$"].user + "]" + "," + txt + "," + diff / 1000 + "," + moment(new Date(diff)).subtract(8, "hour").format("HH:mm:ss") + "," + moment(t).format("YYYY-MM-DD HH:mm:ss") + "\r\n";
                });

                var outfile = entry.path + entry.name + ".csv";
                console.log(outfile);
                await fs.writeFile(outfile, str);
            }
        }
    } catch (err) {
        console.error('处理目录时出错:', err);
    }
}

// 示例调用：替换为你的目录路径
processDirectory('e:\\game\\');
